package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加分类
func CreateCategory(c *gin.Context) {
	var category model.Category
	_ = c.ShouldBindJSON(&category)
	// 查询用户是否存在
	code := model.CheckCategory(category.Name)
	if code == errmsg.SUCCESS {
		model.CreateCategory(&category)
	}
	if code == errmsg.ErrorCategoryNameUsed {
		code = errmsg.ErrorCategoryNameUsed
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   code,
		"category": category,
		"message":  errmsg.GetErrMsg(code),
	})
}

// todo 查询单个分类下的所有文章

// 查询分类列表
func GetCategories(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pagesize"))
	pageNum, _ := strconv.Atoi(c.Query("pagenum"))

	//if pageSize == 0 {
	//	// 通过 -1 消除 Limit 条件
	//	pageSize = -1
	//}
	//if pageNum == 0 {
	//	// 通过 -1 消除 Offset 条件
	//	pageNum = -1
	//}

	categories := model.GetCategories(pageSize, pageNum)
	code := errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":     code,
		"categories": categories,
		"message":    errmsg.GetErrMsg(code),
	})
}

// 编辑分类
func EditCategory(c *gin.Context) {
	var newCategory model.Category
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&newCategory)
	// 查询分类是否存在
	code := model.CheckCategory(newCategory.Name)
	if code == errmsg.SUCCESS {
		model.EditCategory(id, &newCategory)
	}
	if code == errmsg.ErrorCategoryNameUsed {
		c.Abort()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

// 删除分类
func DeleteCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteCategory(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
